package servletAction;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.context.ApplicationContext;

import util.DomainUtils;
import util.FormArgumentsException;
import actionForm.AddContactValidationForm;
import domain.dao.interfaces.IDAOContact;

public class AddContactAction extends Action{

	public ActionForward execute(final ActionMapping pMapping,
			ActionForm pForm, final HttpServletRequest pRequest,
			final HttpServletResponse pResponse) {

		final AddContactValidationForm lForm = (AddContactValidationForm) pForm;
		
		ApplicationContext context = util.SpringUtils.getApplicationContext();

		String first_name = lForm.getFirst_name();
		String last_name = lForm.getLast_name();
		String e_mail = lForm.getE_mail();
		String street = lForm.getStreet();
		String city = lForm.getCity();
		String zip = lForm.getZip();
		String country = lForm.getCountry();
		String mobile = lForm.getMobile();
		String house = lForm.getHouse();
		String work = lForm.getWork();
		String num_siret = lForm.getNum_siret();
		String[] contactgroups = lForm.getContactgroups();


		try {
			if (num_siret == null || num_siret.isEmpty()) {
				IDAOContact daoContact = (IDAOContact) context
						.getBean("beanDAOContact");

				daoContact.addContact( first_name, last_name, e_mail, street,
						city, zip, country, mobile, house, work, contactgroups);

			} else {
				int numSiret = new Integer(num_siret);
				IDAOContact daoContact = (IDAOContact) context
						.getBean("beanDAOContact");
				daoContact.addEntreprise( first_name, last_name, e_mail,
						street, city, zip, country, mobile, house, work,
						numSiret, contactgroups);
			}

			DomainUtils.displayInfoMessage(pRequest,
					DomainUtils.ADD_CONTACT_ALERT_CURRENT_COLOR,
					"Contact successully added.");

		} catch (Exception e) {

			if ((e instanceof FormArgumentsException) == false) {
				pRequest.setAttribute(DomainUtils.ALERT_ERROR_STRING,
						"An error occur on the server.");
			}

			DomainUtils.keepParametersContent(pRequest);
		}
		return pMapping.findForward("stay");
		
	}
}
